package com.vclee.fast.utils.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.vclee.fast.utils.model.Bson;
import com.vclee.fast.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);

    @Pointcut("@annotation(com.vclee.fast.utils.aspect.SysLog)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = method.getAnnotation(SysLog.class);
        String title = sysLog.value();
        if (title.isEmpty()) {
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = signature.getName();
            title = className + "." + methodName + "()";
        }
        StringBuilder builder = new StringBuilder("===> ");
        builder.append(title);
        Object[] args = joinPoint.getArgs();

        HttpServletRequest request = JwtUtils.getContextHttpServletRequest();
        if(request!=null){
            builder.append(",请求票据:").append(JwtUtils.getUserId());
            if (args.length == 1) {
                builder.append(",请求地址:").append(request.getRequestURI());
                String params = Bson.toString(args[0]);
                builder.append(",请求参数:").append(params);
            }else {
                builder.append(",请求地址:").append(request.getRequestURI());
            }
            request.setAttribute("logRsqInfo",builder.toString());
            Object result = joinPoint.proceed();
            request.removeAttribute("logRsqInfo");
            logger.info(builder+",响应参数:" + Bson.toString(result) + ",请求耗时:" + (System.currentTimeMillis() - beginTime));
            return result;
        }else {
            return joinPoint.proceed();
        }
    }
}
